<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="配送日期：" prop="send_times">
              <!-- <el-date-picker
                v-model="form.send_time"
                type="date"
                class="wid220"
                :editable="false"
                placeholder="选择配送日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                @change="getArticleList"
              /> -->
              <el-date-picker
                v-model="form.send_times"
                type="daterange"
                class="wid350"
                value-format="yyyy-MM-dd"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeSendTime"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="发货状态：" prop="order_status">
              <el-select
                v-model.trim="form.order_status"
                placeholder="发货状态"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(sort_status, index) in order_status"
                  :key="index"
                  :label="sort_status"
                  :value="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分拣状态：" prop="order_list_status">
              <el-select
                v-model.trim="form.order_list_status"
                placeholder="分拣状态"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(sort_status, index) in sort_status"
                  :key="index"
                  :label="sort_status"
                  :value="parseInt(index + 1)"
                ></el-option>
              </el-select>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <el-form-item label="配送时间：" prop="send_time_id">
                  <el-select
                    v-model.trim="form.send_time_id"
                    placeholder="配送时间"
                    @change="getArticleList"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(send_time_list, index) in send_time_list"
                      :key="index"
                      :label="send_time_list"
                      :value="parseInt(index)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="配送线路：" prop="line_id">
                  <el-select
                    v-model.trim="form.line_id"
                    placeholder="配送线路"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(line, index) in lines"
                      :key="index"
                      :label="line"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="用户：" prop="nickname">
                  <el-input
                    v-model.trim="form.nickname"
                    placeholder="用户"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item>
                <!-- <el-form-item label="用户" prop="uid">
            <change-user-input
              ref="changeUserInput_form"
              @sendValue="
                data => {
                  form.uid = data.info.user_id;
                }
              "
              @clear="clearzid"
            ></change-user-input>
                 </el-form-item> -->
                <!-- <el-form-item label="子账号" prop="zid">
                <el-select
                  v-model="form.zid"
                  placeholder="子账号"
                  class="wid220"
                  no-data-text
                  filterable
                >
                  <el-option
                    v-for="(zid_time, index) in zid_name"
                    :key="index"
                    :label="zid_time.nickname"
                    :value="zid_time.id"
                  ></el-option>
                </el-select>
                  </el-form-item> -->
                <el-form-item label="用户分组：" prop="group_id">
                  <el-select
                    v-model.trim="form.group_id"
                    placeholder="分组"
                    class="wid220"
                    filterable
                    @change="getArticleList"
                  >
                    <el-option label="所有" :value="parseInt(0)"></el-option>
                    <el-option
                      v-for="(group, index) in alldata.group"
                      :key="index"
                      :label="group"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <el-button @click="pldeliver('order')">批量打印
              <el-tooltip class="item" effect="dark" placement="bottom">
                <div slot="content">
                  注释：打印机纸张需要后进纸，连续打印没有预览效果
                </div>
                <svg
                  aria-hidden="true"
                  class="navbar_svg new_navbar_svg"
                  width="14"
                  height="14"
                >
                  <use xlink:href="#icon-summary_question" />
                </svg> 
              </el-tooltip>
            </el-button>
            <el-button @click="pldeliver('orderPrint')">批次打印
              <el-tooltip class="item" effect="dark" placement="bottom">
                <div slot="content">
                  注释：按照商品已分拣状态进行打印，打印时自动过滤未分拣状态商品，批次打印没有预览效果
                </div>
                <svg
                  aria-hidden="true"
                  class="navbar_svg new_navbar_svg"
                  width="14"
                  height="14"
                >
                  <use xlink:href="#icon-summary_question" />
                </svg>
              </el-tooltip>
            </el-button>
          </div>
          <div>
            <el-checkbox
              v-model="form.print_status"
              @change="sendOrder_index"
              >未打印置顶</el-checkbox
            >
            <el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">
                注释：未打印的订单置顶排序，权重：已发货>分拣未完成>部分分拣>未分拣
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :height="borderHeight"
          :header-cell-class-name="this.$verticaline"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
          @sort-change="sortChange"
        >
          <el-table-column type="selection" />
          <el-table-column
            label="订单号"
            prop="order_sn"
            show-overflow-tooltip
            :width="tableWidth[hash + 'order_sn'] || 180"
          />
          <el-table-column
            label="用户编码"
            prop="user_code"
            show-overflow-tooltip
            sortable="custom"
            :width="tableWidth[hash + 'order_sn'] || 180"
          />
          <!-- <el-table-column label="用户名称" prop="company_name.nickname" /> -->
          <el-table-column
            label="用户名称"
            prop="company_name.nickname"
            :show-overflow-tooltip="true"
            :width="tableWidth[hash + 'company_name.nickname'] || 150"
          >
            <template slot-scope="scope"
              >{{
                scope.row.company_name.nickname
                  ? scope.row.company_name.nickname
                  : scope.row.nickname
              }}<span v-if="scope.row.zid_info"
                >【{{ scope.row.zid_info.nickname }}】</span
              ></template
            >
          </el-table-column>
          <!-- <el-table-column label="配送时间" prop="delivery_time">
              <template slot-scope="scope">{{
                send_time_list[scope.row.send_time_id]
              }}</template>
            </el-table-column> -->
          <el-table-column
            label="分拣状态"
            prop="order_list_status"
            show-overflow-tooltip
            :width="tableWidth[hash + 'order_list_status']"
          >
            <template slot-scope="scope"
              ><span :class="'order' + scope.row.order_list_status">{{
                sort_status[scope.row.order_list_status]
              }}</span></template
            >
          </el-table-column>
          <el-table-column
            label="发货状态"
            prop="order_status"
            show-overflow-tooltip
            :width="tableWidth[hash + 'order_status']"
          >
            <template slot-scope="scope"
              ><span
                :class="
                  scope.row.order_status == 2 || scope.row.order_status == 3
                    ? 'type2'
                    : 'type1'
                "
              >
                {{
                  scope.row.order_status == 2 || scope.row.order_status == 3
                    ? "已发货"
                    : "未发货"
                }}</span
              ></template
            >
            <!-- {{ order_status[scope.row.order_status] }} -->
          </el-table-column>
          <el-table-column
            label="打印次数"
            prop="print_num"
            show-overflow-tooltip
            :width="tableWidth[hash + 'print_num']"
          >
            <template slot-scope="scope"
              ><span :class="'is_print' + scope.row.is_print"
                >{{ scope.row.is_print == 0 ? "未打印" : "打印"
                }}{{
                  scope.row.is_print == 0 ? "" : scope.row.print_num + "次"
                }}</span
              ></template
            >
          </el-table-column>
          <el-table-column
            label="批次明细"
            prop="goods_num"
            show-overflow-tooltip
            :width="tableWidth[hash + 'goods_num']"
          >
            <template slot-scope="{ row }">
              {{ `${row.print_det} (${row.print_total}/${row.goods_num})` }}
            </template>
          </el-table-column>
          <el-table-column
            label="配送路线"
            prop="line_id"
            show-overflow-tooltip
            :width="tableWidth[hash + 'line_id']"
          >
            <template slot-scope="scope">
              {{ lineType(scope.row.line_id) }}
            </template>
          </el-table-column>

          <el-table-column
            label="备注"
            prop="remark"
            show-overflow-tooltip
            :width="tableWidth[hash + 'remark']"
          >
          </el-table-column>

          <el-table-column
            label="管理操作"
            align="center"
            fixed="right"
            prop="operate"
            :width="tableWidth[hash + 'operate'] || 240"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              <!-- <router-link :to="'/order/list/see/' + scope.row.id"> -->
              <el-link type="success" @click="openLook(scope.row.id)"
                >查看</el-link
              >
              <!-- </router-link> -->
              <el-link @click="print(scope.row.id, scope.row.uid)"
                >打印</el-link
              >
              <el-link @click="handleHistory(scope.row)"
                >历史</el-link
              >
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div class="main_num boxdq mg-t-10">
          <div class="main_num_l box">
            <p>
              订单数量：
              <em>{{ alldata.all }}</em>
            </p>
            <p>
              已发货数量：
              <em>{{ alldata.all_ed }}</em>
            </p>
            <p>
              已打印数量：
              <em>{{ alldata.all_print_over }}</em>
            </p>
            <p>
              未打印数量：
              <em>{{ alldata.all_print_no }}</em>
            </p>
          </div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 打印子组件 -->
    <order-print
      ref="printTemplate"
      v-show="false"
      id="printname"
    ></order-print>
    <order-delivery
      ref="NewprintTemplate"
      v-show="false"
      id="printnames"
    ></order-delivery>
    <history-dialog :info="historyInfo" :historyVisible.sync="historyVisible" @histortPrint="histortPrint"></history-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { mapGetters } from "vuex";
import {
  distribution_list,
  useType,
} from "@/api/distribution/distributionList";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
import OrderPrint from "@/views/order/orderPrint.vue";
import OrderDelivery from "@/views/order/orderDelivery.vue";
import historyDialog from "./components/historyDialog.vue"
export default {
  mixins: [mixins],
  computed: {
    ...mapGetters(["avatar"]),
    reverseSum() {
      return this.percent_list.reverse();
    },
    lineType() {
      return function (siteType) {
        return this.lines[siteType];
      };
    },
  },
  components: {
    OrderPrint,
    OrderDelivery,
    historyDialog,
  },
  data() {
    return {
      low_stocks: false,
      // 时间
      parseTime,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 更多
      moredata: false,
      // 列表数据
      list: [],

      info: {
        info: {
          order_sn: "",
          contact: "",
          mobile: "",
          address: "",
          company_name: {
            company_name: "",
          },
          order_list: [],
        },
        order_status: ["未分拣"],
        status: ["未分拣"],
      },
      id: "",
      listLoading: false,
      // 搜索
      form: {
        send_time: null,
        send_times: null,
        send_time_id: null,
        order_list_status: "",
        order_status: "",
        nickname: "",
        print_status: this.print_status ? 1 : 0,
        line_id: null,
        // zid:"",
        group_id: "",
      },
      // zid_name:[],
      print_status: true,
      // 全选
      selectArr: [],
      // 发货状态
      order_status: [],
      // 配送时间
      send_time_list: [],
      // 分拣状态
      sort_status: [],
      // 全部数据
      alldata: {},
      lines: {},

      order_by: 0,

      // 历史弹框 
      historyVisible: false,
      historyInfo: {},
    };
  },
  activated() {
    // 列表
    this.sendOrder_index();
  },
  created() {
    let time = `${parseTime(new Date(), "{y}-{m}-{d}")}, ${parseTime(
      new Date(),
      "{y}-{m}-{d}"
    )}`;
    this.form.send_times = time.split(",");
    this.form.send_time = `${parseTime(new Date(), "{y}-{m}-{d}")}_${parseTime(
      new Date(),
      "{y}-{m}-{d}"
    )}`;
    this.getNumerical(200);
  },
  methods: {
    sortChange({ column, prop, order }) {
      this.order_by = order === 'descending' ? 2 : 1
      this.sendOrder_index()
    },
    startGetting() {
      this.getSearchFor();
    },
    // 搜索并折叠搜索条件
    getSearchFor() {
      this.getArticleList();
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id, uid: item.uid });
      });
    },
    // 监听绑定全选不可勾选
    selectInit(row, index) {
      if (row.order_status == 1 && row.order_list_status == 2) {
        return true;
      } else {
        return false;
      }
    },
    //清除子账号
    // clearzid() {
    //   this.form.uid = "";
    //   this.form.zid = "";
    //   this.zid_name = [];
    // },
    // 获取子账号
    //   uidName(uid) {
    //   let data = Object.assign(
    //     {
    //       sign: Md5(
    //         objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
    //       )
    //     },
    //     apiUrl().name,
    //     { id: uid }
    //   );
    //   user_getMemberInfo(data).then(res => {
    //     if (res.errcode == 0) {
    //       this.form.zid = "";
    //       this.form.zid_name = null;
    //       res.data.subAccount.map((e, ind) => {
    //         if (ind == 0) {
    //           e.id = 0;
    //           e.nickname = "主账号";
    //         }
    //       });
    //       res.data.subAccount.unshift({
    //         id: "",
    //         nickname: "所有"
    //       });
    //       this.zid_name = res.data.subAccount;
    //     } else {
    //       this.$message.error(res.errmsg);
    //     }
    //   });
    // },
    // 批量打印
    pldeliver(type) {
      if (this.selectArr.length != 0) {
        let length = this.selectArr.length;
        this.$confirm(
          `此操作将连续打印【${length}】张配送单,并且打印机需要设置为后进纸,是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            for (let index = 0; index < this.selectArr.length; index++) {
              const item = this.selectArr[index];
              await this.print(item.id, item.uid, type, "continuous");
            }
          })
          .catch(() => {});
      } else {
        this.$message.error("请勾选订单");
      }
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.sendOrder_index();
    },
    // 确认配送日期
    changeSendTime(e) {
      this.form.send_time = e.join("_");
      this.getArticleList();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.sendOrder_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.sendOrder_index();
    },
    changePage(page) {
      this.current.page = page;
      this.sendOrder_index();
    },
    // 列表
    sendOrder_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      if(this.order_by) data.order_by = this.order_by
      // return;
      distribution_list(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          let data = res.data;
          this.order_status = data.order_status;
          this.send_time_list = data.send_time_list;
          this.sort_status = data.sort_status;
          this.list = data.list.data;
          this.alldata = res.data;
          this.lines = data.line;
          this.totalCount = res.data.list.total;
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      delete form.send_times;
      return form;
    },
    openLook(id) {
      this.$router.push({
        path: "/order/list/see",
        query: { id: id },
      });
    },
    // 打印
    print(id, uid, type = "order", continuous, preview = false) {
      return new Promise((resolves, rejects) => {
        useType({ uid }).then((res) => {
          new Promise((resolve, reject) => {
            if (res.errcode == 0) {
              let type = res.is_new == "1" ? "NewprintTemplate" : "printTemplate";
              resolve(type);
            } else {
              this.$message.error(res.errmsg);
            }
          }).then((res) => {
            this.$refs["NewprintTemplate"].show = false;
            this.$refs["printTemplate"].show = false;
            this.$refs[res].$emit("demo", {
              id: id,
              uid: uid,
              type: type,
              continuous: continuous,
              preview: preview,
              cd: (res) => {
                resolves();
              },
            });
          });
        });
      });
    },
    // 历史打印
    histortPrint({id, uid, type, preview}) {
      this.print(id, uid, type, false, preview);
    },
    // 历史
    handleHistory(row) {
      this.historyInfo = row;
      this.historyVisible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 120px);
    .wid350 {
      width: 220px;
    }
  }
  .main_num {
    .mainsu_te {
      position: relative;
      top: -1px;
    }
  }
}

.main_dialog {
  .main_table {
    /deep/.el-table__body-wrapper {
      overflow-y: auto;
      height: 400px;
    }
  }
  .main_xq ul li {
    width: 33.33%;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .progress_list {
    margin-top: 10px;
    p {
      height: 24px;
      line-height: 24px;
    }
    .progress_list_red {
      color: red;
    }
    .progress_list_su {
      color: #03a98e;
    }
  }
}

// 支付状态
.type1 {
  color: $order_color4;
}
.type2 {
  color: $order_color2;
}

.order0 {
  color: $order_color4;
}
.order1 {
  color: $order_color1;
}
.order2 {
  color: $order_color2;
}
.order3 {
  color: $order_color4;
}
.pldeliver_navbar_svg {
  transform: translateY(2px);
}
.new_navbar_svg {
  margin-left: 5px;
  transform: translateY(2px);
  fill: #555;
}
.is_print1 {
  color: #03a98e;
}
.is_print0 {
  color: red;
}
.mainor_sec {
  display: flex;
  position: absolute;
  top: 50px;
  right: 0;
  margin-top: -5px;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
